<template>
  <div class="input-field-StdComments row no-wrap items-start">
    <span
      :class="`field-label ${(Field.Label && Field.Label.trim().length)
        ? '' : 'field-label-empty'} ${Field.Required ? 'required' : ''}`"
      v-if="Field.Label !== void 0"
    >
      <q-tooltip
        v-if="Field.Description"
        anchor="top right"
      >{{$t(Field.Description)}}</q-tooltip>
      {{$t(Field.Label.trim()) || ''}}
      <span
        v-if="Field.Required"
        class="required-mark"
      >*</span>
    </span>

    <div class="input-field-StdComments-wrapper col q-ml-md">
      <q-tabs
        class="input-field-StdComments-tabs"
        v-model="tab"
        align="left"
        no-caps>
        <q-tab
          class="input-field-StdComments-tab"
          v-for="(cmts, idx) in localComments" :key="idx"
          :name="idx"
          :class="{current: cmts.current}">
          <div class="input-field-StdComments-tab-content row items-center no-wrap">
            <div>{{ cmts.Batch }}</div>
            <q-icon
              v-if="tab === idx"
              class="batch-download-icon q-ml-sm" size="xs" name="fas fa-cloud-download-alt"
              @click.stop="exportBatch(cmts)"></q-icon>
          </div>
        </q-tab>
        <q-btn flat dense icon="add"
          class="add-new-batch-btn"
          @click="newBatch">
          <q-tooltip>启动新批次</q-tooltip>
        </q-btn>
      </q-tabs>

      <q-tab-panels
        v-model="tab"
        v-if="localComments.length">
        <q-tab-panel
          v-for="(cmts, idx) in localComments" :key="idx"
          :name="idx">
          <StdDevStandardComments
            class="q-px-md"
            :indentChild="false"
            :data="cmts.Comments"
            :ReadOnly="Field.ReadOnly"
          ></StdDevStandardComments>

          <div class="no-data-content"
            v-if="!cmts.Comments.length">
            <div
              class="no-data-text absolute-center"
              style="padding-left: 12px;opacity: 0.8;">暂无信息</div>
          </div>
        </q-tab-panel>
      </q-tab-panels>
    </div>
  </div>
</template>

<script>
import { exportFile } from 'quasar';
import { InputFieldMixin } from 'eis-admin-mixins';

export default {
  name: 'InputFieldStdComments',
  mixins: [InputFieldMixin],
  fieldInfo: {
    Category: '标准制修订',
    Label: '标准草案意见反馈',
    Value: 'StdComments',
    Description: '',
    Extra: [
      {
        Label: '多选',
        Name: 'Multiple',
        Type: 'Boolean',
      },
    ],
  },
  data() {
    return {
      tab: 0,
    };
  },
  watch: {
    fieldData() {
      const currentBatch = this.fieldData.findIndex((c) => c.current);
      if (currentBatch >= 0) {
        this.tab = currentBatch;
      } else {
        this.tab = 0;
      }
    },
  },
  computed: {
    localComments() {
      const comments = this.fieldData || [];

      for (let i = 0; i < comments; i += 1) {
        const btch = comments[i];
        btch.Comments = btch.Comments || [];

        const ret = [];
        for (let j = 0; j < btch.Comments.length; j += 1) {
          const c = btch.Comments[j];

          if (!c.CommentTo) {
            ret.push(c);
          } else {
            const parent = btch.Comments.find((p) => p.id === c.CommentTo.id);
            if (parent) {
              parent.children = parent.children || [];

              parent.children.push(c);
            }
          }
        }

        btch.Comments = ret;
      }

      return comments;
    },
  },
  methods: {
    startNewBatch() {
      const fieldsData = {};
      this.showNotifyDialog({
        content: '启动新批次',
        warning: '启动后用户将无法看到所有旧批次中的意见反馈，只能在新批次中提交新的意见反馈。是否确定启动新批次？',
        okText: '启动',
        canCancel: true,
        cancelText: '取消',
        fields: [
          {
            Type: 'String',
            Name: 'Batch',
            Required: true,
            PlaceHolder: '请输入新批次名称',
            Info: {
              MaxLength: 100,
              Classes: 'input-field-StdComments-new-batch-input',
            },
          },
        ],
        fieldsData,
      }, () => {
        if (fieldsData.Batch) {
          this.postRequest(`/stddev/mgmt/comment/batch/${this.$route.params.id}`, {
            batch: fieldsData.Batch,
          }).then((res) => {
            if (res.msg === 'OK') {
              this.$q.notify({
                message: '新批次启动成功',
                color: 'positive',
                position: 'top',
                timeout: 2000,
              });

              // clear the default batch
              if ((this.localComments.length === 1) && (this.localComments[0].Batch === '默认批') && (this.localComments.findIndex((c) => c.current) < 0)) {
                this.localComments[0].Batch = fieldsData.Batch;
                this.tab = 0;
              }

              if (this.localComments.findIndex((c) => c.Batch === fieldsData.Batch) === -1) {
                this.localComments.forEach((cmts) => {
                  cmts.current = false;
                });
                this.localComments.push({
                  Batch: fieldsData.Batch,
                  Comments: [],
                  current: true,
                });

                this.$nextTick(() => {
                  this.tab = this.localComments.length - 1;
                });
              } else {
                this.tab = this.localComments.findIndex((c) => c.Batch === fieldsData.Batch);
              }
            }
          });
        }
      });
    },
    newBatch() {
      const currentBatch = this.localComments.find((c) => c.current);
      // warning if the current batch has no comments
      if (currentBatch && !currentBatch.Comments.length) {
        this.showNotifyDialog({
          content: '启动新批次',
          warning: '当前批次下没有意见反馈，启动新批次后将无法看到所有旧批次中的意见反馈，只能在新批次中提交新的意见反馈。是否确定启动新批次？',
          okText: '启动',
          canCancel: true,
          cancelText: '取消',
        }, () => {
          this.startNewBatch();
        });
      } else {
        this.startNewBatch();
      }
    },
    exportBatch(batch) {
      if (!batch?.Comments?.length) {
        this.showNotifyDialog({
          warning: '当前批次下没有意见反馈，无法导出。',
          okText: '确定',
          canCancel: false,
        });

        return;
      }

      this.showNotifyDialog({
        content: '导出批次',
        warning: '导出批次后将生成一个CSV文件，文件中包含了该批次下的所有意见反馈。是否确定导出？',
        okText: '导出',
        canCancel: true,
        cancelText: '取消',
      }, () => {
        exportFile(
          `${batch.Batch}.csv`,
          `批次,用户,时间,内容\n${batch.Comments.map((cmt) => `${cmt.批次},${cmt.UserName},${cmt.LastUpdateDate},${cmt.Content}`).join('\n')}`,
        );
      });
    },
    showNotifyDialog(options, func) {
      this.$MsgDialog({ type: '', ...options })
        .then(() => {
          if (func && typeof func === 'function') {
            func();
          }
        })
        .catch(() => { });
    },
  },
};
</script>

<style lang="scss" scoped>
.input-field-StdComments-wrapper {
  border: 1px solid #d2d2d2;
  border-radius: 4px;

  .input-field-StdComments-tabs {
    border-bottom: 1px solid #d2d2d2;

    .input-field-StdComments-tab {
      &.current {
        color: $primary;
      }
    }
  }

  .add-new-batch-btn {
    margin-left: 10px;
  }

  .no-data-content {
    height: 200px;
    min-height: 200px;
  }
}
</style>

<style lang="scss">
.input-field-StdComments-new-batch-input {
  width: 300px !important;
}
</style>
